import os
import re
import random
import time


def get_name(file_path):
    pattern = r'[\u4e00-\u9fa5]+'
    names = re.findall(pattern, file_path)
    if names:
        return names[0]
    return None


def get_stu_num(file_path):
    pattern = r'230\d+'
    stu_nums = re.findall(pattern, file_path)
    if stu_nums:
        return stu_nums[0]
    return None


def extract_student_info(file_path):
    # 正则表达式匹配学号和姓名
    num = get_stu_num(file_path)
    name = get_name(file_path)
    if num:
        return num, name
    return None


def scan_folder(folder_path):
    student_info_set = set()

    # 遍历文件夹中的所有文件和子文件夹
    for root, dirs, files in os.walk(folder_path):
        for file_name in files + dirs:
            full_path = os.path.join(root, file_name)
            info = extract_student_info(file_name)
            if info:
                stu_info = (info[0], info[1], file_name)
                student_info_set.add(stu_info)

    return student_info_set


def count_down(num):
    print("倒计时：")
    counted = 0
    for i in range(int(num)):
        time.sleep(1)
        print(num - counted)
        counted += 1
    return


def random_chose_from_txt(txt_path):
    with open(txt_path, 'r', encoding='utf-8') as rf:
        txt = rf.read()

    tex_lis = txt.strip().split('\n')[1:]
    tex_lis = [x.split(',')[:3] for x in tex_lis]
    return tex_lis


def main():
    folder_path = input("请输入文件夹路径：")

    if not os.path.exists(folder_path):
        print("输入的路径不是一个有效的文件夹或者文件夹不存在！")
        return

    count_down(5)

    # student_info_set = scan_folder(folder_path)
    student_info_set = random_chose_from_txt(folder_path)
    if not student_info_set:
        print("没有找到符合条件的学生信息。")
        return

    # 随机抽取一位学生
    selected_student = random.choice(list(student_info_set))
    print(f"随机抽取的学生信息: \n\n学号姓名: {selected_student[0]}, {selected_student[1]}, --备注：{selected_student[-1]}")


if __name__ == "__main__":
    main()